import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-alter-taoti',
  templateUrl: './alter-taoti.component.html',
  styleUrls: ['./alter-taoti.component.css']
})
export class AlterTaotiComponent implements OnInit {
  validateForm: FormGroup;
  id = 0;
  taoti: any;

  constructor(private fb: FormBuilder,
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe((params) => {
      this.id = params.id;
      if (this.id != null) {
        this.http
          .get(`/api/TaoTi/findById?id=${this.id}`)
          .subscribe(response => {
            this.taoti = response;
            this.validateForm = this.fb.group({
              name: [this.taoti.name, [Validators.required]],
              count: [this.taoti.count, [Validators.required]],
              minute: [this.taoti.minute, [Validators.required]],
              difficulty: [this.taoti.difficulty, [Validators.required]],
              score: [this.taoti.score, [Validators.required]]
            });
          });
      }
    });

    if (this.taoti == null) {
      this.validateForm = this.fb.group({
        name: [null, [Validators.required]],
        count: [null, [Validators.required]],
        minute: [null, [Validators.required]],
        difficulty: [null, [Validators.required]],
        score: [null, [Validators.required]]
      });
    }
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      if (i) {
        this.validateForm.controls[i].markAsDirty();
      }
    }
    if (this.validateForm.status !== 'VALID') {
      return;
    }

    this.http
      .post(`/api/TaoTi/save`, JSON.stringify(this.validateForm.value), {
        headers: new HttpHeaders({
          'Content-type': 'application/json'
        })
      })
      .subscribe(response => {
        response = response as boolean;
        if (response) {
          this.router.navigate(['/content/taoti']);
        }
      });
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

}
